package cn.gov.msa.util;


import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisUtils {
	
   
    private static RedisTemplate<String,Object>  redisTemplate;
    static {
    	ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); 
    	redisTemplate = (RedisTemplate<String, Object>) ctx.getBean("redisTemplate");
    }
    /**
     * 向Hash中添加值
     * @param key      可以对应数据库中的表名
      * @param field    可以对应数据库表中的唯一索引
     * @param value    存入redis中的值
     */
    public void hset(String key, String field, Object value) {
    	try {
	        if(key == null || "".equals(key)){
	            return ;
	        }
	        redisTemplate.opsForHash().put(key, field, value);
    	}catch(Exception e) {}
    }
    
    /**
     * 从redis中取出值
     * @param key
     * @param field
     * @return
     */
    public Object hget(String key, String field){
    	try {
	        if(key == null || "".equals(key)){
	            return null;
	        }
	        return  redisTemplate.opsForHash().get(key, field);
    	}catch(Exception e) {
    		return null;
    	}
    }
    
    /**
     * 判断 是否存在 key 以及 hash key
     * @param key
     * @param field
     * @return
     */
    public boolean hexists(String key, String field){
    	try {
	        if(key == null || "".equals(key)){
	            return false;
	        }
	        return redisTemplate.opsForHash().hasKey(key, field);
    	}catch(Exception e) {
    		return false;
    	}
    }
    
    /**
     * 查询 key中对应多少条数据
     * @param key
     * @return
     */
    public long hsize(String key) {
    	try {
	        if(key == null || "".equals(key)){
	            return 0L;
	        }
	        return redisTemplate.opsForHash().size(key);
    	}catch(Exception e) {
    		return 0L;
    	}
    }
    
    /**
     * 删除
     * @param key
     * @param field
     */
    public void hdel(String key, String field) {
    	try {
	        if(key == null || "".equals(key)){
	            return;
	        }
	        redisTemplate.opsForHash().delete(key, field);
    	}catch(Exception e) {
    		
    	}
    }
    public void delete(String prex) {
        Set<String> keys = redisTemplate.keys(prex);
        if (CollectionUtils.isNotEmpty(keys)) {
            redisTemplate.delete(keys);
        }
    }
    
    public boolean setIfAbsent(String key, String value){
		if (key == null || "".equals(key.trim())) {
			return false;
		}
    	return redisTemplate.opsForValue().setIfAbsent(key, value);
    }
    public static void main(String[] args) {
		RedisUtils aa = new RedisUtils();
		aa.delete("queryLeftMenu*");
		System.err.println("OK");
	}
}
